// src/hooks/useCreateAccountForm.ts

import { useState } from 'react';
import type { CreateAccountFormData } from '@/types/types';
import { createAccount } from '@/services/authService';

export function useCreateAccountForm() {
  const [form, setForm] = useState<CreateAccountFormData>({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
  });

  const [emailError, setEmailError] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [firstNameError, setFirstNameError] = useState('');
  const [lastNameError, setLastNameError] = useState('');
  const [generalError, setGeneralError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');

  const setFirstName = (firstName: string) => {
    setForm((prev) => ({ ...prev, firstName }));
    if (firstNameError) setFirstNameError('');
    if (generalError) setGeneralError('');
  };

  const setLastName = (lastName: string) => {
    setForm((prev) => ({ ...prev, lastName }));
    if (lastNameError) setLastNameError('');
    if (generalError) setGeneralError('');
  };

  const setEmail = (email: string) => {
    setForm((prev) => ({ ...prev, email }));
    if (emailError) setEmailError('');
    if (generalError) setGeneralError('');
  };

  const setPassword = (password: string) => {
    setForm((prev) => ({ ...prev, password }));
    if (passwordError) setPasswordError('');
    if (generalError) setGeneralError('');
  };

  const validate = () => {
    let valid = true;

    if (!form.firstName.trim()) {
      setFirstNameError('First name is required');
      valid = false;
    } else {
      setFirstNameError('');
    }

    if (!form.lastName.trim()) {
      setLastNameError('Last name is required');
      valid = false;
    } else {
      setLastNameError('');
    }

    if (!/^[\w-.]+@[\w-]+\.[a-zA-Z]{2,}$/.test(form.email)) {
      setEmailError('Invalid email format');
      valid = false;
    } else {
      setEmailError('');
    }

    const hasLetter = /[a-zA-Z]/.test(form.password);
    const hasNumber = /\d/.test(form.password);
    const hasSymbol = /[^a-zA-Z0-9]/.test(form.password);
    const isLongEnough = form.password.length >= 8;

    if (!isLongEnough || !hasLetter || !hasNumber || !hasSymbol) {
      setPasswordError('Password must be at least 8 characters, including letters, numbers and symbols');
      valid = false;
    } else {
      setPasswordError('');
    }

    return valid;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setGeneralError('');
    setSuccessMessage('');

    if (!validate()) return;

    try {
      await createAccount({
        first_name: form.firstName,
        last_name: form.lastName,
        email: form.email,
        password: form.password,
      });

      setSuccessMessage('Account created successfully!');

      // Clear form after successful registration
      setForm({
        firstName: '',
        lastName: '',
        email: '',
        password: '',
      });

    } catch (error: unknown) {
      console.error('Registration error:', error);
      setGeneralError('Registration failed. Please try again.');
    }
  };

  const register = async () => {
    setGeneralError('');
    setSuccessMessage('');
    if (!validate()) return false;

    try {
      await createAccount({
        first_name: form.firstName,
        last_name: form.lastName,
        email: form.email,
        password: form.password,
      });

      setSuccessMessage('Account created successfully!');

      // Clear form after successful registration
      setForm({
        firstName: '',
        lastName: '',
        email: '',
        password: '',
      });

      // Don't navigate away - stay on create-account page for admin
      return true;
    } catch (error: unknown) {
      console.error('Registration error:', error);
      setGeneralError('Registration failed. Please try again.');
      return false;
    }
  };

  return {
    ...form,
    setFirstName,
    setLastName,
    setEmail,
    setPassword,
    handleSubmit,
    emailError,
    passwordError,
    firstNameError,
    lastNameError,
    generalError,
    successMessage,
    register
  };
}